from django import forms
from django.core.validators import RegexValidator, ValidationError


class SensitivityWordValidator:
    """自定义验证器类"""

    def __call__(self, value):
        word_list = ["xx", "sb"]
        for word in word_list:
            if value.find(word) != -1:
                raise ValidationError("用户名不能包含某些敏感词汇")  # 抛出异常


class RegisterForm(forms.Form):
    """
    注册后端验证的表单类
    属性名与input的name属性值保持一致
    """
    name = forms.CharField(
        # 基本验证
        required=True,
        min_length=6,
        max_length=10,
        # 基本验证的错误信息
        error_messages={
            "required": "用户名必填",
            "min_length": "长度不能小于6",
            "max_length": "长度不能大于10",
        },
        # 验证器
        validators=[
            RegexValidator(regex=r"^[a-zA-Z0-9_]{6,10}$", message="用户名只能包含6-10位的字母数字下划线"),
            SensitivityWordValidator(),  # 使用自定义验证器类
        ]
    )
    password = forms.CharField(
        required=True,
        min_length=6,
        max_length=10,
        error_messages={
            "required": "密码必填",
            "min_length": "长度不能小于6",
            "max_length": "长度不能大于10",
        }
    )